import axios from 'axios';
import { Message } from 'element-ui';
import { getToken, getClientId, removeToken } from '@/utils/auth';

const querystring = require('querystring');

// 是否开发模式
export const isDev = false;

let env = process.env.NODE_ENV;
if (env === 'production') {
  env = process.env.API_ENV;
}
if (isDev) {
  env = 'dev';
}
const obj = {
  dev: 'http://localhost:8080',
  stg: 'http://47.97.179.230:8092',
  development: 'http://47.97.179.230:8081',
  dist: 'http://47.97.179.230:8092'
};
const host = obj[env] || obj.dist;

// Axios 单一实例
let instance = null;
const getAxiosInstance = () => {
  const token = getToken();
  const clientId = getClientId();
  if (!instance) {
    instance = axios.create({
      timeout: 3000,
      headers: {
        'K-Access-Token': token,
        'K-Client': `id:${clientId}`
      }
    });

    instance.interceptors.response.use(res => res.data, (error) => {
      if (!error.response) {
        Message.error('网络不给力，请稍后再试');
        return Promise.reject(error);
      }
      if (error.response.status === 403) {
        Message.error('用户不能重复登录');
        removeToken();
        setTimeout(() => {
          location.reload();
        }, 1500);
        return Promise.reject(error);
      }
    });
  }
};

export const getRequest = url => ((params) => {
  getAxiosInstance();

  if (isDev) {
    const reqUrl = `${host}/${url}?${querystring.stringify(params)}`;
    return instance.get(reqUrl);
  } else {
    let reqUrl = url;
    const keys = Object.keys(params || {});
    for (const key of keys) {
      reqUrl = reqUrl.replace(`{${key}}`, params[key]);
    }
    reqUrl = `${host}/${reqUrl}`;
    return instance.get(reqUrl);
  }
});

export const postRequest = url => ((params) => {
  getAxiosInstance();

  params = params || {};
  const reqUrl = `${host}/${url}`;
  return instance.post(reqUrl, params);
});

export const deleteRequest = url => ((params) => {
  getAxiosInstance();

  if (isDev) {
    const reqUrl = `${host}/${url}?${querystring.stringify(params)}`;
    return instance.get(reqUrl);
  } else {
    let reqUrl = '';
    const keys = Object.keys(params || {});
    for (const key of keys) {
      reqUrl = url.replace(`{${key}}`, params[key]);
    }
    reqUrl = `${host}/${reqUrl}`;
    return instance.delete(reqUrl);
  }
});

// 为登录接口专设
export const directPostRequest = url => ((params) => {
  const reqUrl = `${host}/${url}?${querystring.stringify(params)}`;
  return axios.post(reqUrl).then(res => res.data);
});

export default {
  isDev,
  deleteRequest,
  getRequest,
  directPostRequest,
  postRequest
};
